package com.adresvseti.wallpaperoid;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import com.adresvseti.wallpaperoid.constants.Settings;
import com.adresvseti.wallpaperoid.helpers.WallpaperImageAdapter;
import com.adresvseti.wallpaperoid.models.Wallpaper;
import com.adresvseti.wallpaperoid.services.DecodeBitmapTask;
import com.adresvseti.wallpaperoid.services.DownloadBinaryTask;
import com.adresvseti.wallpaperoid.services.IDecodeBitmapCallback;
import com.adresvseti.wallpaperoid.services.IDownloadBinaryCallback;
import com.adresvseti.wallpaperoid.services.WallpapersService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;


public class MainActivity extends Activity implements OnItemClickListener {

	static final String STATE_WALLPAPERS = "wallpapers";
	
	private GridView gridView;
	private ArrayList<Wallpaper> wallpapers;
	private WallpaperImageAdapter gridViewAdapter;
	private ProgressDialog progressDialog;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_main);
        
        
        // restoring state
        if (savedInstanceState != null)
        {
            ArrayList<Wallpaper> ws = savedInstanceState.getParcelableArrayList(STATE_WALLPAPERS);
            if (ws != null && ws.size() > 0)
            {
            	wallpapers = ws;
            }
            else {
            	// loading
            	wallpapers = getWallpapers();
            }
        }
        else {
        	// loading
        	wallpapers = getWallpapers();
        }
        
        
        gridView = (GridView) findViewById(R.id.wallpapers_view);
        gridView.setColumnWidth(Settings.THUMB_MAXWIDTH);
        gridView.setOnItemClickListener(this);
        
        
        gridViewAdapter = new WallpaperImageAdapter(this, wallpapers);
		gridView.setAdapter(gridViewAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        
    	// Always call the superclass so it can restore the view hierarchy
        super.onRestoreInstanceState(savedInstanceState);
       
        
    }
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {

    	// saving state
        savedInstanceState.putParcelableArrayList(STATE_WALLPAPERS, wallpapers);
        
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }
    
    public ArrayList<Wallpaper> getWallpapers() {
        
    	// retrieving list of wallpapers
    	Resources res = getResources();
    	TypedArray wallpapersArray = res.obtainTypedArray(R.array.wallpapers);
    	
    	ArrayList<Wallpaper> ws = new ArrayList<Wallpaper>();
    	for (int i = 0; i < wallpapersArray.length(); i++) {
			
    		// retrieving file name
    		int resId = wallpapersArray.getResourceId(i, 0);
    		String fileName = getResources().getResourceEntryName(resId);
    		int wallpaperId = Integer.parseInt(fileName.substring(6));
    		
    		Wallpaper w = new Wallpaper(wallpaperId, resId);
    		ws.add(w);
		}
    	
		return ws;
		
    	/*
        ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
        	
        	WallpapersService service = new WallpapersService();
        	service.getWallpapersAsync(2, new IGetWallpapersCallback() {
				
				@Override
				public void success(List<Wallpaper> result) {
					
					// loading wallpapers
					loadWallpapers(result);
					
				}
			});
        	        	
        } else {
        	Log.d(Settings.DEBUG_TAG, "No network connection available.");
        }
        */
    }    
    
    /*
    private void loadWallpapers(List<Wallpaper> wallpapers)
    {
    	this.wallpapers = wallpapers;
		
		// setting grid view layout
    	gridViewAdapter = new WallpaperImageAdapter(this, this.wallpapers);
		gridView.setAdapter(gridViewAdapter);
		
		// loading wallpapers
		for (Wallpaper wallpaper : wallpapers) {
			loadWallpaper(wallpaper);
		}
    }
    
    
    private void loadWallpaper(final Wallpaper wallpaper)
    {
    	final ImageService imageService = new ImageService();
    	imageService.downloadImageAsync(wallpaper.thumbUrl, new IDownloadBinaryCallback() {
			
			@Override
			public void success(InputStream inputStream) {
				
				imageService.decodeBitmapAsync(inputStream, Settings.THUMB_MAXWIDTH, Settings.THUMB_MAXHEIGHT, new IDecodeBitmapCallback() {
					
					@Override
					public void success(Bitmap result) {
						
						wallpaper.thumbBitmap = result;
						gridViewAdapter.notifyDataSetChanged();
					}
				});
				
			}
		});
    }
    */
    
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        
    	// showing loading dialog
    	progressDialog = new ProgressDialog(this);
    	progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	progressDialog.setMessage("Loading wallpaper...");
    	progressDialog.show();
    	progressDialog.setCanceledOnTouchOutside(false);
    	
    	
    	
    	WallpaperManager wm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE);
    	
    	// downloading wallpaper
    	WallpapersService service = new WallpapersService();
       
        final int width = wm.getDesiredMinimumWidth();
        final int height = wm.getDesiredMinimumHeight();
    	
    	String thumbUrl = service.getWallpaperUrl((int)id, width, height, 3, 100);

    	final Activity activity = this;
    	DownloadBinaryTask downloadTask = new DownloadBinaryTask(new IDownloadBinaryCallback() {

    		@Override
    		public void success(InputStream inputStream) {

    			
    			DecodeBitmapTask decodeTask = new DecodeBitmapTask(width, height, new IDecodeBitmapCallback() {
					
					@Override
					public void success(Bitmap result) {
						
						// hiding loading dialog
						progressDialog.dismiss();
						
						if (result != null)
				    	{
							setupWallpaper(result);
				    	}
						else {
							Log.d(Settings.DEBUG_TAG, "Could not load wallpaper");
							
							AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(activity);                      
						    dlgAlert.setTitle("Error"); 
						    dlgAlert.setMessage("Could not load wallpaper.");
						}
					}
				});

    			decodeTask.execute(inputStream);
    		}
    	});
    		
    	downloadTask.execute(thumbUrl);	
    }
    
    private void setupWallpaper(Bitmap wallpaperBitmap)
    {
    	if (wallpaperBitmap == null)
    	{
    		return;
    	}
    	
    	try
    	{
    		WallpaperManager wm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE);
    		wm.setBitmap(wallpaperBitmap);
    		
    		//wm.suggestDesiredDimensions(wallpaperBitmap.getWidth(), wallpaperBitmap.getHeight());
    		wm.suggestDesiredDimensions(wm.getDesiredMinimumWidth(), wm.getDesiredMinimumHeight());
    		
    		//wm.setWallpaperOffsetSteps(2, 0);
			
			AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);                      
		    dlgAlert.setTitle("Wallpaper updated"); 
		    dlgAlert.setMessage("Wallpaper has been setted up.");
		    
		    final Activity activity = this;
		    dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int whichButton) {
		        	activity.finish();
		        }
		   });
		    
		    dlgAlert.setCancelable(true);
		    dlgAlert.create().show();
    	
    	} catch (IOException e) {
    		Log.d(Settings.DEBUG_TAG, "Could not setup wallpaper");
    	}    	
    }
    
}
